import { getLngLat } from '@gis/lib/components/AMap/js/AMapUtils.js';
import { isNumLike } from '@gis/lib/utils/dataType.js';
import get from 'lodash-es/get.js';

export class BasicMarkers {
  constructor() {
    this.dataList = [];
    this.markers = [];
    this.preIntercept = {};
  }
  ready() {
    if (!this.promise) {
      this.promise = new Promise(async (resolve) => {
        const list = await this.getDataAsync();
        if (Array.isArray(list)) {
          this.dataList = list.reduce((res, item) => {
            if (!item || typeof item !== 'object') return res;
            let lng = get(item, 'lnglat[0]');
            let lat = get(item, 'lnglat[1]');
            if (!isNumLike(lng) || !isNumLike(lat)) {
              const lngLat = getLngLat(item);
              if (lngLat) {
                lng = lngLat.lng;
                lat = lngLat.lat;
              }
            }
            if (!isNumLike(lng) || !isNumLike(lat)) return res;
            item.lnglat = [lng, lat];
            return res.concat([item]);
          }, []);
        }
        this.createMarkers();
        resolve();
      });
    }
    return this.promise;
  }
  addIntercept(ins) {
    if (ins && typeof ins.preIntercept === 'object') {
      Object.keys(this.preIntercept).forEach((key) => {
        ins.preIntercept[key] = this.preIntercept[key];
      });
    }
  }
  getDataAsync() {
    /* 子类自行实现 */
    return new Promise((resolve) => resolve([]));
  }
  getMarkers() {
    return this.markers.slice(0);
  }
  getMarker(ins) {
    if (typeof ins.getMarker === 'function') {
      ins = ins.getMarker();
    }
    if (ins instanceof AMap.Marker) {
      return ins;
    }
  }
  createMarkers() {
    this.markers = this.dataList.reduce((res, item) => {
      const ins = this.createMarker(item);
      if (!ins || !(ins.marker instanceof AMap.Marker)) return res;
      this.addIntercept(ins);
      return res.concat([ins]);
    }, []);
  }
  createMarker(data) {
    /*
     * 子类自行实现
     * 需要返回一个Marker实例
     * 或者具有一个可以返回marker实例的getMarker方法的实例或对象
     * */
    // console.log(data);
    return {
      marker: new AMap.Marker({}),
      getMarker() {
        return this.marker;
      },
    };
  }
}
